☰ See All Chapters |
Java switch on Strings
Up to Java 1.6 the expression used in a switch statement must have an integral or enumerated type, or be of a class type in which the class has a single conversion function to an integral or enumerated type.
switch (expression) { case value_expression: statement(s); break; /* optional */ case value_expression: statement(s); break; /* optional */ /* you can have any number of case statements */ default: /* Optional */ statement(s); } |
From Java 7 expression used in a switch statement can be of type String also.
class A { public static void selectString(String s) { switch (s) { case "AAA": System.out.println("AAA is selected"); break; case "BBB": System.out.println("BBB is selected"); break; case "CCC": System.out.println("CCC is selected"); break; } } } public class Test { public static void main(String[] args){ A a= new A(); a.selectString("AAA"); } } |
Prior JDK7
class A { public void selectString(String s) { if (s.equals("AAA")) { System.out.println("AAA is selected"); } if (s.equals("BBB")) { System.out.println("BBB is selected"); } if (s.equals("CCC")) { System.out.println("CCC is selected"); } } }
public class Test { public static void main(String[] args){ A a= new A(); a.selectString("AAA"); } } |
All Chapters